﻿using System.Collections;
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using 人员管理8;

namespace WPF人员管理8
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window 
    {
        private PersonUtils personUtils;
        MainModel model;


        public MainWindow()
        {
            InitializeComponent();
            // 当前数据的上下文
            model = new MainModel(this);
            this.DataContext = model;
            personUtils = new PersonUtils();

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            cb_sex.Items.Add("男");
            cb_sex.Items.Add("女");
            cb_sex.SelectedIndex = 0;

            RefreshPersons();
        }


        private void RefreshPersons()
        {
            IEnumerable<Person> enumerable = personUtils.SelectAll();
            IEnumerable<Person> filteredItems = enumerable.Where(item => !string.IsNullOrEmpty(item.Name));
            DG1.ItemsSource = filteredItems;
        }


        /// <summary>
        /// 选中一条记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DG1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            IList selectedItems = DG1.SelectedItems;
            foreach(Person? person in selectedItems)
            {
                if(person == null) continue;
                model.SelId = person.ID;
                model.PName = person.Name;
                model.PAge = person.Age+"";
                model.PSex = person.Sex;
                model.PAddr = person.Addr;
                if (person.Sex.Trim().Equals("男"))
                { 
                    cb_sex.SelectedIndex = 0;
                }
                else
                {
                    cb_sex.SelectedIndex = 1;
                }
            }
        }

        /// <summary>
        /// 清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Clear_Click(object sender, RoutedEventArgs e)
        {
            model.PName = "";
            model.PAge = "";
            model.PSex = "";
            model.PAddr = "";
        }

        private void Btn_OpenDlg1_Click(object sender, RoutedEventArgs e)
        {
            Window1 window1 = new Window1();
            // window1.Show(); // 非模态窗口
            window1.ShowDialog(); // 模态窗口
        }

        /// <summary>
        /// 打开一个自定义控件的窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn2_Click(object sender, RoutedEventArgs e)
        {
            Window2 window2 = new Window2();
            window2.ShowDialog();
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_close_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }


    /// <summary>
    /// mvvm 设计模式，页面和model自动的绑定
    /// </summary>
    public class MainModel: INotifyPropertyChanged
    {
        /// <summary>
        /// public delegate void PropertyChangedEventHandler(object? sender, PropertyChangedEventArgs e);
        /// </summary>
        public event PropertyChangedEventHandler? PropertyChanged;

        private string _name;
        private string _age;
        private string _sex;
        private string _addr;
        private long _selId;

        private MainWindow _window;

        private PersonUtils personUtils;

        public MainModel()
        {
            personUtils = new PersonUtils();
        }

        public MainModel(MainWindow window )
        {
            _window = window;
            personUtils = new PersonUtils();
        }


        public MainWindow MW
        {
            get
            {
                return _window;
            }
        }


        public long SelId
        {
            get { return _selId; }
            set { _selId = value; } 
        }


        // 页面控件和属性进行绑定，双向绑定。
        // 属性值变化，页面显示也跟着变化。
        // 页面变化，属性值也跟着变化。
        public string PName
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
                OnPropertyChanged(nameof(PName));
            }
        }
        public string PAge
        {
            get { return _age; }
            set
            {

                _age = value;
                OnPropertyChanged(nameof(PAge));
            }
        }
        public string PSex
        {
            get
            {
                return _sex;
            }
            set
            {
                _sex = value;
                OnPropertyChanged(nameof(PSex));
            }
        }
        public string PAddr
        {
            get
            {
                return _addr;
            }
            set
            {
                _addr = value;
                OnPropertyChanged(nameof(PAddr));
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }


        /// <summary>
        /// 命令
        /// </summary>
        private ICommand _insertCommand;
        private ICommand _updateCommand;
        private ICommand _deleteCommand;
        private ICommand _searchCommand;

        public ICommand InsertCommand
        {
            get
            {
                return _insertCommand ?? (_insertCommand = new RelayCommand(InsertAction, CanExecute));
            }
        }

        public ICommand UpdateCommand
        {
            get
            {
                return _updateCommand ?? (_updateCommand = new RelayCommand(UpdateAction, CanExecute));
            }
        }

        public ICommand DeleteCommand
        {
            get
            {
                return _deleteCommand ?? (_deleteCommand = new RelayCommand(DeleteAction, CanExecute));
            }
        }

        public ICommand SearchCommand
        {
            get
            {
                return _searchCommand ?? (_searchCommand = new RelayCommand(SearchAction, CanExecute));
            }
        }
        /// <summary>
        /// 搜索
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void SearchAction()
        {
            IEnumerable<Person> enumerable = personUtils.FindPersons(PName,PAge,PSex,PAddr);
            MW.DG1.ItemsSource = enumerable;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void DeleteAction()
        {
            if (SelId != 0)
            {
                bool b = personUtils.DeletePerson(SelId);
                if (b)
                {
                    RefreshPersons();
                }
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void UpdateAction()
        {
            if (SelId != 0)
            {
                bool b = personUtils.EditPerson(SelId,PName,PAge,PSex,PAddr);
                if (b)
                {
                    RefreshPersons();
                }
            }
        }


        /// <summary>
        /// 插入数据
        /// </summary>
        private void InsertAction()
        {
            // 执行命令的逻辑代码  

            bool b = personUtils.InsertPerson(PName, PAge, PSex, PAddr);
            if (b)
            {
                RefreshPersons();
            }
        }

        /// <summary>
        /// 刷新
        /// </summary>
        private void RefreshPersons()
        {
            IEnumerable<Person> enumerable = personUtils.SelectAll();
            IEnumerable<Person> filteredItems = enumerable.Where(item => !string.IsNullOrEmpty(item.Name));
            MW.DG1.ItemsSource = filteredItems;
        }

        /// <summary>
        /// 是否能执行插入数据的方法
        /// </summary>
        /// <returns></returns>
        private bool CanExecute()
        {
            // 返回一个布尔值来决定命令是否可以执行  
            return true; // 根据实际条件判断返回true或false  
        }
    }


    class RelayCommand:ICommand
    {
        private Action _execute;
        private Func<bool> _canExecute;

        public RelayCommand() { }

        public RelayCommand(Action execute, Func<bool> canExecute)
        {
            this._execute = execute;
            this._canExecute = canExecute;
        }

        public event EventHandler? CanExecuteChanged
        {
            add
            {
                if(_canExecute != null)
                {
                    CommandManager.RequerySuggested += value;
                }
            }

            remove
            {
                if(_canExecute != null)
                {
                    CommandManager.RequerySuggested -= value;
                }
            }
        
        }

        public bool CanExecute(object? parameter)
        {
            return _canExecute();
        }

        public void Execute(object? parameter)
        {
            if(_canExecute())
            {
                _execute();
            }
        }
    }




}